package com.example.autumn.web;

import com.example.autumn.annotation.Autowired;
import com.example.autumn.annotation.Bean;
import com.example.autumn.annotation.Configuration;
import com.example.autumn.annotation.Value;
import jakarta.servlet.ServletContext;

import java.util.Objects;

/**
 * @author liuzhiyong
 * @date 2023/11/9
 * description:
 */
@Configuration
public class WebMvcConfiguration {

    private static ServletContext servletContext = null;

    static void setServletContext(ServletContext ctx) {
        servletContext = ctx;
    }

    /**
     * 创建视图解析器的Bean
     *
     * @param servletContext servlet容器
     * @param templatePath 模板路径
     * @param templateEncoding 模板编码
     * @return {@link ViewResolver }
     * @author liuzhiyong
     * @date 2023/11/9
     */
    @Bean(initMethod = "init")
    ViewResolver viewResolver(@Autowired ServletContext servletContext,
                              @Value("${autumn.web.freemarker.template-path:/WEB-INF/templates}") String templatePath,
                              @Value("${autumn.web.freemarker.template-encoding:UTF-8}") String templateEncoding) {
        return new FreeMarkerViewResolver(servletContext, templatePath, templateEncoding);
    }

    /**
     * servlet容器
     */
    @Bean
    ServletContext servletContext() {
        return Objects.requireNonNull(servletContext, "ServletContext is not set.");
    }

}
